package lesson04.作业.作业02;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 面试题： 写一个固定容量同步容器，拥有put和get方法，以及getCount方法
 * 能够支持2个生产者线程以及10个消费者线程的阻塞调用
 */
public class ThreadDome02<T> {

    private final List<T> lists = new ArrayList<>();
    private final  Integer MAX = 10;
    private volatile Integer count = 0;

    public synchronized void put(T t)  {
        while (lists.size() == MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lists.add(t);
        count++;
        System.out.println(t);
        this.notify();
    }

    public synchronized T get() {
        T t = null;
        while (lists.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = lists.get(0);
        lists.remove(0);
        count--;
        System.out.println("         "+Thread.currentThread().getName() + " - " + t);
        this.notify();
        return  t;
    }
    public Integer getCount(){
        return lists.size();
    }

    public static void main(String[] args) throws Exception {

        Thread[] serve = new Thread[2];
        Thread[] clent = new Thread[10];
        ThreadDome02<String> dome = new ThreadDome02<>();

        // 生产者
        for (int i = 0; i < serve.length; i++) {
                serve[i] = new Thread(() -> {
                    for (int k = 0; k < 25; k++) {
                    // System.out.println("启动生产者.... " + Thread.currentThread().getName());
                    dome.put(Thread.currentThread().getName() +"& "+ k);
                    }
                }, "S-" + i);
        }
        // 消费者
        for (int i = 0; i < clent.length; i++) {
            clent[i] = new Thread(() -> {
                System.out.println("启动消费者--" + Thread.currentThread().getName());
                for (int k = 0; k < 5; k++) {
                    dome.get();
                }

            }, "P->" + i);
        }

        for (int i = 0; i < serve.length; i++) serve[i].start();
        // TimeUnit.SECONDS.sleep(1);
        for (int i = 0; i < clent.length; i++) clent[i].start();


    }
}
